<?php

namespace App\Admin\Controllers;

use App\Models\Brand;
use App\Models\Vendor;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Models\Channel;
use App\Models\Product;
use App\Models\Category;
use App\Models\User;
use App\Models\AttributeGroup;
use Encore\Admin\Layout\Content;
use App\Admin\Actions\ProductAction\Skus;
use App\Admin\Actions\ProductAction\Slides;
use App\Admin\Actions\ProductAction\Images;
use App\Admin\Actions\ProductAction\Expresses;
use App\Admin\Actions\ProductAction\ExtraExpresses;
use App\Admin\Actions\ProductAction\Restore;
use Illuminate\Support\Facades\Storage;
use Encore\Admin\Controllers\AdminController;
use App\Services\MakeProductThumbnail\MakeProductThumbnail;

class ProductsController extends AdminController
{
    protected $title = '商品列表';

	protected function product($id = null)
	{
		if ($id and ($product = Product::find($id))) {
			return $product;
		}
		return null;
	}

    protected function grid()
    {
        $grid = new Grid(new Product());
        $grid->model()->orderByDesc('id');
       
        $grid->column('id', 'ID');
        $grid->column('cover', '封面')->display(function ($value) {
	        if (! Storage::exists($value)) {

	        	dd($value);
		       // $this->update(['cover' => null]);
		        return '';
	        } else {
		        return _grid_image($value);
	        }
        });
        $grid->column('title_long', '名称')->limit(50);
        $grid->column('category_id', '分类')->display(function ($value) {
	       
		    return isset($this->category) ?  $this->category->name : '';
	        
        });
        $grid->column('price_lowest', '会员价');
        $grid->column('price_market', '市场价');
        //$grid->column('group_number', '参团人数');
       
        $grid->column('sold_count', '销量');
        //$grid->column('command_star', '推荐指数');
        $grid->column('is_sale', '上架')->bool();
      /*  $grid->column('is_seckill', '秒杀')->bool();
        $grid->column('is_higher_rewards', '是否高佣金')->bool();
        $grid->column('is_ice', '是否冰点')->bool();
        $grid->column('is_quality', '是否超高品质')->bool();
        $grid->column('is_low', '是否全网低价')->bool();*/
        //$grid->column('is_pop', '强烈推荐')->bool();
       /* $grid->column('is_rec', '今日主推')->bool();*/
      //  $grid->column('is_group', '是否团购商品')->bool();


        $grid->disableRowSelector();
        $grid->disableExport();
        $this->gridFilter($grid);
        $this->gridActions($grid);

        return $grid;
    }

    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableView();
		    if (request('_scope_') == 'trashed') {
			    $actions->add(new Restore());
		    }
		    $actions->add(new Skus());
		    $actions->add(new Slides());
		    $actions->add(new Images());
		    $actions->add(new ExtraExpresses());
		    $actions->add(new Expresses());
	    });
    }

    protected function gridFilter(Grid $grid)
    {
	    $grid->filter(function (Grid\Filter $filter) {
		    $filter->expand();

		    $filter->column(1/2, function (Grid\Filter $filter) {
		    	$filter->disableIdFilter();
			    $filter->equal('id', '商品ID');
			    $filter->like('title', '短标题查询');
			    $filter->equal('vendor_id', '供应商查询')->select(Vendor::all()->pluck('name', 'id'));

		    });

		    $filter->column(1/2, function (Grid\Filter $filter) {
			    $filter->equal('number', '货号查询');
			    $filter->like('title_long', '长标题查询');
			    $filter->like('category_id', '分类查询')->select(Category::selectOptions());
		    });

	    	$filter->scope('trashed', '回收站')->onlyTrashed();
	    	$filter->scope('sale_on', '上架商品')->where('is_sale', true);
	    	$filter->scope('sale_off', '下架商品')->where('is_sale', false);
	    	//$filter->scope('seckill', '秒杀商品')->where('is_seckill', true);
	    	//$filter->scope('is_pop', '强烈推荐')->where('is_pop', true);
	    	/*$filter->scope('is_ice', '冰点商品')->where('is_ice', true);
	    	$filter->scope('is_higher_rewards', '高佣金商品')->where('is_higher_rewards', true);
	    	$filter->scope('is_quality', '是否超高品质')->where('is_quality', true);
	    	$filter->scope('is_low', '是否全网低价')->where('is_low', true);
	    	$filter->scope('is_rec', '今日主推')->where('is_rec', true);*/
	    	//$filter->scope('is_group', '团购商品')->where('is_group', true);
	    });
    }

	public function edit($id, Content $content)
	{
		return $content
			->title($this->title())
			->description($this->description['edit'] ?? trans('admin.edit'))
			->body($this->form($id)->edit($id));
	}

	protected function form($id = null)
    {
        $form = new Form(new Product());

        $product = $this->product($id);
        $this->formFilesCheck($id);

        $form->tab('基础信息', function ($form) {
	        $this->formBase($form);
        })->tab('上架设置', function ($form) {
	        $this->formSale($form);
        });

	    $this->formTools($form);
        $this->formFooter($form);

        //$this->formSaved($form, $id);
        return $form;
    }

    protected function formFilesCheck($id = null)
    {
	    if (!$product = $this->product($id)) {return;}

	    if (! Storage::exists($product->cover)) {
		    $product->cover = null;
		    $product->save();
	    }

	    foreach ($product->skus as $sku) {
		    if (! Storage::exists($sku->pic)) {
			    $sku->pic = null;
			    $sku->save();
		    }
	    }

	    foreach ($product->slides as $slide) {
		    if (! Storage::exists($slide->slide)) {
			    $slide->delete();
		    }
	    }

	    foreach ($product->images as $image) {
		    if (! Storage::exists($image->image)) {
			    $image->delete();
		    }
	    }
    }

    protected function formCategory(Form $form)
    {
	    $form->select('category_id', '所属分类')
		    ->options(Category::selectOptions())
		    ->rules(['nullable', function ($attribute, $value, $fail) {
			    if ($value and Category::isParent($value)) {
				    return $fail('请选择末级分类');
			    }
			    return true;
		    }]);
    }

    protected function formBase(Form $form)
    {
	    $form->select('vendor_id', '商品供应商')
		    ->options(Vendor::trees());

	    $this->formCategory($form);

	   $form->select('brand_id', '所属品牌')
		    ->options(Brand::tree());

	    $form->select('attribute_group_id', '属性组')
		    ->options(AttributeGroup::tree());

	    $form->divider();

	    $form->text('title', '商品标题')->rules('required');

	    $form->text('title_long', '商品长标题')->rules('required');

	    $form->text('reason', '上架理由');

	    $form->text('code', '商品货号')
		    ->rules('required|nullable|regex:/[a-zA-Z0-9_\-]/');

	    $form->image('cover', '封面图片')
		    ->uniqueName()
		    ->creationRules('required');

	    $form->textarea('description', '商品说明')
		    ->help('非必填项');

		//$form->text('command_user_id', '推荐人')->default(0);
		    
		//$form->text('command_link', '推荐链接')->default('');

		//$form->number('command_star', '推荐指数')->default(0);
		//$form->number('group_cards_number', '开团卡数量')->default(1);

		//$form->number('group_number', '参团人数量')->default(1);

		//$form->rate('reward_rate', '开团成功奖励比例')->default(100);

	    $form->divider();

	   /* $form->number('order', '排序')
		    ->min(1)->default(1)
		    ->help('NOTE: 仅做相对排序')
		    ->rules('required|regex:/[1-9]+/', [
			    'required' => '显示顺序为必填项',
			    'regex' => '显示顺序只能为正整数',
		    ]);*/
    }

    protected function formSale(Form $form)
    {
	   /* $form->radio('is_seckill', '是否秒杀商品')
		    ->options(config('site.bool'))
		    ->default(false);*/

	    $form->radio('is_support', '是否支持七天无理由')
		    ->options(config('site.bool'))
		    ->default(false);
		/* $form->radio('is_own', '是否自营')
		    ->options(config('site.bool'))
		    ->default(false);*/
		
	    $form->divider();

	    //$form->radio('is_delivery_free', '支持全场包邮')->options(config('site.bool'))->default(true);
	    $form->radio('is_returnable', '支持售后退货')->options(config('site.bool'))->default(true);

	    $form->divider();

	    $form->radio('is_sale', '上架')->options(config('site.bool'))->default(false);
	   /* $form->radio('is_higher_rewards', '高佣金')->options(config('site.bool'))->default(false);
	    $form->radio('is_ice', '是否冰点')->options(config('site.bool'))->default(false);
	    $form->radio('is_quality', '是否超高品质')->options(config('site.bool'))->default(false);
	    $form->radio('is_low', '是否全网低价')->options(config('site.bool'))->default(false);*/
	    //$form->radio('is_pop', '强烈推荐')->options(config('site.bool'))->default(false);
	    //$form->radio('is_rec', '今日主推')->options(config('site.bool'))->default(false);
	    //$form->radio('is_group', '团购商品')->options(config('site.bool'))->default(true);

    }

	protected function formTools(Form $form)
	{
		$form->tools(function (Form\Tools $tools) use ($form) {
			$tools->disableView();
			$tools->disableDelete();
		});
	}

	protected function formFooter(Form $form)
	{
		$form->footer(function (Form\Footer $footer) {
			$footer->disableViewCheck();
			$footer->disableCreatingCheck();
			$footer->disableEditingCheck();
		});
	}

	protected function formSaved(Form $form , $id)
	{
		/*$form->saved(function () use ($form) {
			
			$product = $this->product($form->model()->id) ?? null;
			app(MakeProductThumbnail::class, ['product' => $product])->make();
		});*/
	}
}
